package com.ailink.correctdistortiondemo

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import androidx.activity.ComponentActivity
import com.ailink.correctdistortiondemo.DistortionCorrector.cameraMatrix
import com.ailink.correctdistortiondemo.DistortionCorrector.correctDistortion
import com.ailink.correctdistortiondemo.DistortionCorrector.distCoeffs
import org.opencv.android.OpenCVLoader

class MainActivity : ComponentActivity() {
    val iv by lazy { findViewById<ImageView>(R.id.iv) }
    val llParams by lazy { findViewById<LinearLayout>(R.id.llParams) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)

        //val params = arrayOf("fx", "cx", "fy", "cy", "k1", "k2", "p1", "p2", "k3")
        // 调整优先级建议（按影响程度排序）：
        // 1. 径向畸变系数：k1 > k2 > k3
        // 2. 切向畸变系数：p1/p2
        // 3. 相机矩阵参数：cx/cy > fx/fy

        // 径向畸变系数：k1, k2, k3
        val kRange = doubleArrayOf(-0.5, 0.5, 100.0)
        newParamView("k1", distCoeffs[0], kRange[0], kRange[1], kRange[2]) { progress ->
            distCoeffs[0] = progress
        }
        newParamView("k2", distCoeffs[1], kRange[0], kRange[1], kRange[2]) { progress ->
            distCoeffs[1] = progress
        }
        newParamView("k3", distCoeffs[4], kRange[0], kRange[1], kRange[2]) { progress ->
            distCoeffs[4] = progress
        }

        // 切向畸变系数：p1, p2
        val pRange = doubleArrayOf(-0.5, 0.5, 100.0)
        newParamView("p1", distCoeffs[2], pRange[0], pRange[1], pRange[2]) { progress ->
            distCoeffs[2] = progress
        }
        newParamView("p2", distCoeffs[3], pRange[0], pRange[1], pRange[2]) { progress ->
            distCoeffs[3] = progress
        }

        // 焦距
        val focalLenRange = doubleArrayOf(100.0, 3000.0, 1.0)
        newParamView("fx", cameraMatrix[0][0], focalLenRange[0], focalLenRange[1], focalLenRange[2]) { progress ->
            cameraMatrix[0][0] = progress
        }
        newParamView("fy", cameraMatrix[1][1], focalLenRange[0], focalLenRange[1], focalLenRange[2]) { progress ->
            cameraMatrix[1][1] = progress
        }

        OpenCVLoader.initLocal()
        updateImage()

        // 主点坐标 (和当前图片尺寸挂钩)
        val w = iv.drawable.intrinsicWidth.toDouble()
        cameraMatrix[0][2] = w / 2.0
        newParamView("cx", cameraMatrix[0][2], 0.0, w, 1.0) { progress ->
            cameraMatrix[0][2] = progress
        }
        val h = iv.drawable.intrinsicHeight.toDouble()
        cameraMatrix[1][2] = h / 2.0
        newParamView("cy", cameraMatrix[1][2], 0.0, h, 1.0) { progress ->
            cameraMatrix[1][2] = progress
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        finish()
    }

    private fun newParamView(
        name: String, defValue: Double,
        minValue: Double, maxValue: Double,
        rate: Double, onValueUpdate: (Double) -> Unit,
    ) {
        newParamVh().apply {
            tvName.text = name
            sbValue.apply {
                progress = (defValue * rate).toInt()
                tvValue.text = defValue.toString()
                min = (minValue * rate).toInt()
                max = (maxValue * rate).toInt()
                setOnSeekBarChangeListener(object : ValueChangeListener() {
                    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                        val realValue = progress / rate
                        onValueUpdate(realValue)
                        tvValue.text = realValue.toString()
                        updateImage()
                    }
                })
            }
        }
    }

    private fun updateImage() {
        // 假设你从资源或存储中加载了一个畸变的Bitmap
        val distortedBitmap: Bitmap = BitmapFactory.decodeStream(assets.open("test_3.png"))

        // 应用畸变校正
        val undistortedBitmap = correctDistortion(distortedBitmap)

        iv.setImageBitmap(undistortedBitmap)
    }

    private fun newParamVh(): VH {
        return VH(View.inflate(this, R.layout.seek_param, null).apply {
            llParams.addView(this)
        })
    }

    private class VH(view: View) {
        val tvName: TextView = view.findViewById(R.id.tvName)
        val tvValue: TextView = view.findViewById(R.id.tvValue)
        val sbValue: SeekBar = view.findViewById(R.id.sbValue)
    }

    private abstract class ValueChangeListener : OnSeekBarChangeListener {
        /*override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
        }*/

        override fun onStartTrackingTouch(seekBar: SeekBar?) {
        }

        override fun onStopTrackingTouch(seekBar: SeekBar?) {
        }

    }
}